package jh.jianguan.springboot.util.common.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;

/**
 * @description: JedisUtil 工具类
 * @author: guoc
 * @createDate: 2020/12/30 10:56
 */
@Component
public class JedisUtil {

    private static JedisUtil jedisUtil;
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";


    @Autowired
    private JedisPool jedisPool;

    @PostConstruct
    public void initialize() {
        jedisUtil= this;
        jedisUtil.jedisPool = this.jedisPool;
    }

    /**
     * jedis 分布式锁
     * expireSecond 为毫秒值
     * @return boolean
     * @author guoc
     * @date 2020/12/30 17:11
     */
    public static boolean lock(String redisKey, String redisValue, int expireSecond) {
        String result=null;
        Jedis jedis=null;
        try {

                jedis = jedisUtil.jedisPool.getResource();
                result  = jedis.set(redisKey, redisValue, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireSecond);
                if (LOCK_SUCCESS.equals(result)){
                    return true;
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != jedis) {
                jedisUtil.jedisPool.returnResourceObject(jedis);
            }
        }
        return false;
    }



}
